<?php
/**
 **************************************************************************************************************************************
 *热敏单（中通电子面单 Thermal paper）
 *zhouzhixiang@kuaidihelp.com
 **************************************************************************************************************************************
 */
namespace soa\partner\zt;
use artisan\http;
use artisan\format;
use soa\partner\partnerCommon;//热敏单公用方法（电子面单公用方法）
use artisan\db;
use artisan\cache;

class ztThermalPaper{
    //配置信息
    //接口地址(测试用)
    //protected $zto_service_url = 'http://testpartner.zto.cn/client/interface.php';
    //接口地址(正式环境用)
    protected $zto_service_url = 'http://partner.zto.cn/client/interface.php';
    //服务项目名称
    protected $zto_partner = '';
    //erp系统签名
    protected $zto_pass = '';

    public function __construct($zto_partner,$zto_pass){

        //$this->zto_partner = 'test';//测试用
        //$this->zto_pass    = 'ZTO123';//测试用

        $this->zto_partner = $zto_partner;      //test//商家ID
        $this->zto_pass    = $zto_pass;         //ZTO123//商家接口密码
    }

    public function getZtoServiceUrl(){
        return $this->zto_service_url;
    }

    public function getZtoPass(){
        return $this->zto_pass;
    }

    public function getZtoPartner(){
        return $this->zto_partner;
    }

    /**
     * 获取大头笔
     */
    public function getCharacters($sendcity, $sendaddress, $receivercity, $receiveraddress){
        //验证传入参数是否完整
        if(empty($sendcity) || empty($receivercity)){
            return array();
        }
        $content = [
            //"id"            =>                    //快递单号
            "sendcity"         => $sendcity,        //发件人省市区
            "sendaddress"      => $sendaddress,     //发件人详细地址
            "receivercity"     => $receivercity,    //收件人省市区
            "receiveraddress"  => $receiveraddress  //收件人详细地址
        ];
        //测试
        //logdebug($content,'zt_partner_characters_original_content');
        $content=base64_encode(json_encode($content));

        $partner = $this->getZtoPartner();
        $datetime = date('Y-m-d H:i:s',time());
        $pwd = $this->getZtoPass();
        $verify=md5($partner.$datetime.$content.$pwd);
        //调用中通接口获取大头笔
        $retFirstTimeObj = http::post($this->getZtoServiceUrl(), array(
            "style"    => 'json',
            "func"     => 'order.marke',
            "partner"  => $partner,
            "datetime" => $datetime,
            "content"  => $content,
            "verify"   => $verify,
        ));
                //以下为接口返回结果样例
                //成功：
                // {"mark":"武汉仙桃",  /*这个是普通面单的大头笔*/"marke":"武汉转仙桃" /*这个是电子面单的大头笔*/}
                //失败：
                //{"result": "false","code": "s08","remark": "非法的账户信息"}

        //使用当前快递员的zto_partner和zto_pass获取大字
        if(empty($retFirstTimeObj)){//返回空
            $errMsg = '请求超时';
            $needSecondTime = true;//需要第二次尝试
        }else{//有返回结果
            $retFirstTimeArr = json_decode($retFirstTimeObj, true);
            if(json_last_error() == 0){
                if(isset($retFirstTimeArr['code']) && !empty($retFirstTimeArr['code'])){//{"result": "false","code": "s08","remark": "非法的账户信息"}
                    logDebug($retFirstTimeObj, 'jsonDecodeZtGetCharsetZero');
                    $errMsg = $retFirstTimeArr['code'].'-'.$retFirstTimeArr['remark'];
                    $needSecondTime = true;//需要第二次尝试
                }else{//正确返回大字
                    //将正确获取大字的zto_partner和zto_pass存入缓存，供其他人尝试
                    $ztoPartnerAndPass = json_encode(['partner'=>$partner,'pwd'=>$pwd]);
                    cache::set('ztoPartnerAndPass', $ztoPartnerAndPass, $ttl = 600);
                    return $retFirstTimeArr;//返回电子面单大头笔
                }
            }else{
                logDebug($retFirstTimeObj, 'jsonDecodeZtGetCharsetError');
                $errMsg = '数据解析失败';
                $needSecondTime = true;//需要第二次尝试
            }
        }

        if($needSecondTime){//需要尝试第二次
            //从缓存中获取其他已经成功获取过大字的快递员的中天账号密码（大客户账号密码）
            $ztoPartnerAndPassObj = cache::get('ztoPartnerAndPass');
            if(empty($ztoPartnerAndPassObj)){
                return $errMsg;
            }else{
                $ztoPartnerAndPassArr = json_decode($ztoPartnerAndPassObj,true);
                $partner  = $ztoPartnerAndPassArr['partner'];
                $datetime = date('Y-m-d H:i:s',time());
                $pwd      = $ztoPartnerAndPassArr['pwd'];
                $verify=md5($partner.$datetime.$content.$pwd);
                //调用中通接口获取大头笔
                $retSecondTimeObj = http::post($this->getZtoServiceUrl(), array(
                    "style"    => 'json',
                    "func"     => 'order.marke',
                    "partner"  => $partner,
                    "datetime" => $datetime,
                    "content"  => $content,
                    "verify"   => $verify,
                ));

                if(empty($retSecondTimeObj)){//返回空
                    return $errMsg;
                }else{//有返回结果
                    $retSecondTimeArr = json_decode($retSecondTimeObj, true);
                    if(json_last_error() == 0){
                        if(isset($retSecondTimeArr['code']) && !empty($retSecondTimeArr['code'])){//{"result": "false","code": "s08","remark": "非法的账户信息"}
                            logDebug($retSecondTimeObj, 'jsonDecodeZtGetCharsetZero');
                            return $errMsg;//返回第一次尝试时中通接口返回的错误信息
                        }else{//正确返回大字
                            //将正确获取大字的zto_partner和zto_pass存入缓存，供其他人尝试
                            $ztoPartnerAndPass = json_encode(['partner'=>$partner,'pwd'=>$pwd]);
                            cache::set('ztoPartnerAndPass', $ztoPartnerAndPass, $ttl = 600);
                            return $retSecondTimeArr;//返回电子面单大头笔
                        }
                    }else{
                        logDebug($retSecondTimeObj, 'jsonDecodeZtGetCharsetError');
                        return $errMsg;
                    }
                }
            }
        }

        /*此段代码已弃用
        if(empty($ret)){//中通接口无返回结果
            return '请求超时';
        }else{//有返回结果
            //解析返回的结果
            $result = json_decode($ret, true);
            if(json_last_error() == 0){
                if(!empty($result['remark']) && !empty($result['code'])){//{"result": "false","code": "s08","remark": "非法的账户信息"}
                    logDebug($ret, 'jsonDecodeZtGetCharsetZero');
                    return $result['remark'];
                }
                return $result;//返回电子面单大头笔
            }else{
logDebug($ret, 'jsonDecodeZtGetCharsetError');
                return '数据解析失败';
            }
        }
        */
    }

    /**
     * 获取中通运单号
     */
    public function getNo($datas){
        $data = $datas[0];
//logdebug('enter','enter');
        if(empty($data) || !is_array($data)){
            return array();
        }
//logdebug($datas,'getNo_datas');
        //以下为必填字段开始
        $id               = empty($data['order_number']) ? raise(1009,'缺少订单号') : $data['order_number'] ;//'123456789';//订单号
        $sender_name      = empty($data['sender_name']) ? raise(1009,'缺少发件人') : $data['sender_name'] ;//'变活扣旗舰店';//发件人
        // $sender_mobile    = empty($data['sender_mobile']) ? '' : $data['sender_mobile'] ;//'13912345678';//和sender_phone二选一//发件人手机号码
        // $sender_phone     = empty($data['sender_phone']) ? '' : $data['sender_phone'] ;//'021-87654321';//和sender_mobile二选一//发件人电话号码
        if($data['sender_phone']){
            if((substr($data['sender_phone'],0,1) == 1) && (strlen($data['sender_phone']) == 11)){
                $sender_mobile = $data['sender_phone'];//发件人手机号//13912345678
            }else{
                $sender_phone  = $data['sender_phone'];//发件人固定电话//021-87654321
            }
        }else{
            raise(1009,'缺少发件人电话');
        }
        $sender_province  = empty($data['sender_province']) ? raise(1009,'缺少发件人省市区') : $data['sender_province'] ;
        $sender_city      = empty($data['sender_city']) ? raise(1009,'缺少发件人省市区') : $data['sender_city'] ;//'上海市,上海市,虹口区';//必填//发件人所在城市，如“上海市,上海市,青浦区,华新镇,华志路,123号”
        $sender_area      = empty($data['sender_area']) ? raise(1009,'缺少发件人省市区') : $data['sender_area'] ;
        $sender_address   = empty($data['sender_address']) ? raise(1009,'缺少发件人详细地址') : $data['sender_address'] ;//'三门路100号';//必填//发件人路名门牌等地址信息

        $receiver_name    = empty($data['receiver_name']) ? raise(1009,'缺少收件人') : $data['receiver_name'] ;//'尹静';//必填//收件人姓名
        // $receiver_mobile  = empty($data['receiver_mobile']) ? '' : $data['receiver_mobile'] ;//'13687654321';//和receiver_phone二选一//收件人手机号码
        // $receiver_phone   = empty($data['receiver_phone']) ? '' : $data['receiver_phone'] ;//'010-22226789';//和receiver_mobile二选一//收件人电话号码
        if($data['receiver_phone']){
            if((substr($data['receiver_phone'],0,1) == 1) && (strlen($data['sender_phone']) == 11)){
                $receiver_mobile = $data['receiver_phone'];//收件人手机号//13687654321
            }else{
                $receiver_phone  = $data['receiver_phone'];//收件人固定电话//010-22226789
            }
        }else{
            raise(1009,'缺少收件人电话');
        }
        $receiver_province= empty($data['receiver_province']) ? raise(1009,'缺少收件人省市区') : $data['receiver_province'] ;
        $receiver_city    = empty($data['receiver_city']) ? raise(1009,'缺少收件人省市区') : $data['receiver_city'] ;//'上海市,上海市,长宁区';//必填//收件人所在城市，如“上海市,上海市,青浦区,华新镇,华志路,123号”
        $receiver_area    = empty($data['receiver_area']) ? raise(1009,'缺少收件人省市区') : $data['receiver_area'] ;
        $receiver_address = empty($data['receiver_address']) ? raise(1009,'缺少收件人详细地址') : $data['receiver_address'] ;//'北翟路1178号（鑫达商务楼）1号楼415室';//必填//收件人路名门牌等地址信息
        //必填字段结束

        //以下为选填字段开始
        $collect_sum      = empty($data['collect_sum']) ? '' : $data['collect_sum'] ;//选填//代收款
        $goods_name       = empty($data['goods_name']) ? '' : $data['goods_name'] ;//选填//货品名称
        $remark           = empty($data['remark']) ? '' : $data['remark'] ;//选填//备注
        //选填字段结束

        //以下为中通接口需要的参数：
        $content = array(
            'id'       =>$id,//必填//订单号
            'sender'   => array(
//                'mailno'   =>$mailno,//选填//快递单号
                'name'     =>$sender_name,//必填//发件人姓名
                'mobile'   =>$sender_mobile,//和phone二选一//发件人手机号码
                'phone'    =>$sender_phone,//和mobile二选一//发件人电话号码
                'city'     =>$sender_province.','.$sender_city.','.$sender_area,//必填//发件人所在城市，如“上海市,上海市,青浦区,华新镇,华志路,123号”
                'address'  =>$sender_address,//必填//发件人路名门牌等地址信息
                ),
            'receiver' => array(
                'name'     =>$receiver_name,//必填//收件人姓名
                'mobile'   =>$receiver_mobile,//和phone二选一//收件人手机号码
                'phone'    =>$receiver_phone,//和mobile二选一//收件人电话号码
                'city'     =>$receiver_province.','.$receiver_city.','.$receiver_area,//必填//收件人所在城市，如“上海市,上海市,青浦区,华新镇,华志路,123号”
                'address'  =>$receiver_address,//必填//收件人路名门牌等地址信息
                ),
            'items'    => array(
                array(
                    'name'     =>$goods_name,//选填//货品名称
                    ),
                ),
            'remark'   =>$remark,//选填//备注
            );
        //测试
//logdebug($content,'zt_partner_send_original_content');
        $content=base64_encode(json_encode($content));

        $partner = $this->getZtoPartner();
        $datetime = date('Y-m-d H:i:s',time());
        $pwd = $this->getZtoPass();
        $verify=md5($partner.$datetime.$content.$pwd);
        //调用中通接口提交电子面单数据
        $ret = http::post($this->getZtoServiceUrl(), array(
            "style" => 'json',
            "func" => 'order.submit',
            "partner" =>$partner,
            "datetime" => $datetime,
            "content" => $content,
            "verify" => $verify,
        ));
        if(empty($ret)){//中通接口无返回结果
            return '请求超时';
        }else{//有返回结果
            //解析返回的结果
            $result = json_decode($ret, true);
            //测试
//logdebug($content,'zt_partner_send_base64_content');
//logdebug($result,'zt_partner_send_result');
            if(json_last_error() ==0 /*&& $result['result'] == 'true'*/){
//logDebug($result,'ztNoJsonDecodeError');
//                $return['0'] = $result['keys']['mailno'];
                $return['0'] = $result['result'] ? $result['keys']['mailno'] : $result['remark'];
                return $return;//返回请求接口结果
            }else{
logDebug($ret, 'jsonDecodeZtGetNOError');
                return '数据解析失败';
            }
        }
    }

    /**
     * 查询中通电子面单单号规则
     */
/*
    public function getZtNoRule($cm_phone){
        $scan_access_info = \artisan\db::connect('kd_pda')->table('tbl_scan_courier_zt')->select('emp_no,emp_name,emp_pwd,cm_phone,branch_no,branch_name,key,imei,index_shop_id,home_shop_id')->getOne(array('cm_phone' => $cm_phone, 'switch' => 'on', 'state' => 'approve'));
//logdebug($scan_access_info,'zt_send_datas_scan_access_info');
        if(empty($scan_access_info)){
            raise(4016, "快递员信息有误");
        }else{
            $ztObj = new \soa\parter\zt\pda();
            $openId = \artisan\cache::get($scan_access_info['emp_no'] ."openid:");   //获取openid
            if(empty($openId)){//若无openid重新登录
                $ztObj->login($scan_access_info);
                $openId = \artisan\cache::get($scan_access_info['emp_no'] ."openid:");
                if(empty($openId)){
                    raise(4016, "系统异常，请稍后重试");
                }
            }
        }


$xml = '<?xml version="1.0" encoding="utf-8" ?>
<root>
<h>
  <ver>4.0</ver>
  <optype>G010</optype>
  <manufacturer>KUAIBAOAPP</manufacturer>
  <u_company>'.$scan_access_info['branch_no'].'</u_company>
  <u_code>'.$scan_access_info['emp_no'].'</u_code>
  <sys_sn>'.$scan_access_info['imei'].'</sys_sn>
  <key>'.$scan_access_info['key'].'</key>
  <openid>'.$openId.'</openid>
</h>
 <d>
 </d>
</root>';
        $ret = $this->sendToZto($xml);
        if(isset($ret['Success'])){
//logDebug($ret,'getZtNoRule');
            return  $ret;
        }else{
            return 'faild';//"error":{"reason":"XXX"}
        }

    }
*/

    /**
     * 从缓存中获取中通电子面单匹配规则
     */


    public function getZtRule(){
        $ztRules = \artisan\cache::get('ztRules:rule_express');
        if(is_array($ztRules) && isset($ztRules['rule_order']) && $ztRules['rule_order']){
            $ztRules=$ztRules['rule_order'];
        }else{
            $ztRules='';
        }
        return $ztRules;
    }



    /**
     * 提交电子面单数据
     */
    public function send($datas){
        //测试用数据
        // $datas = [
        //     "0"=>[
        //         "order_number"      =>"762589871234",
        //         "branch_name"       =>"长宁一部",
        //         "cm_name"           =>"测试",
        //         "cm_id"             =>"237",
        //         "cm_phone"          =>"18983137943",
        //         "express_number"    =>"762852148965",
        //         "datetime"          =>"2016-07-21",
        //         "sender_name"       =>"张三",
        //         "sender_phone"      =>"15812345678",
        //         "sender_province"   =>"上海",
        //         "sender_city"       =>"上海市",
        //         "sender_area"       =>"长宁区",
        //         "sender_address"    =>"北翟路100号",
        //         "receiver_name"     =>"李四",
        //         "receiver_phone"    =>"13312345678",
        //         "receiver_province" =>"北京",
        //         "receiver_city"     =>"北京市",
        //         "receiver_area"     =>"通州区",
        //         "receiver_address"  =>"南京西路",
        //         "goods_name"        =>"衣服淘宝",
        //         ]
        // ];

        $data = $datas[0];
        unset($datas);
//logdebug($data,'zt_send_data');
//        if(empty($data) || !is_array($data)){
//            raise(1009,'参数错误');
//        }

        $order_number     = empty($data['order_number'])? /*raise(1009)*/'' : $data['order_number'] ;//订单号
        $branch_name      = empty($data['branch_name'])? /*raise(1009)*/'' : $data['branch_name'] ;//网点名称
        $cm_name          = empty($data['cm_name'])? /*raise(1009)*/'' : $data['cm_name'] ;//快递员姓名
        $cm_id            = empty($data['cm_id'])? /*raise(1009)*/'' : $data['cm_id'] ;//快递员id
        $cm_phone         = empty($data['cm_phone']) ? /*raise(1009)*/'' : $data['cm_phone'] ;//快递员手机号
        //以下为必填字段开始
        $express_number   = empty($data['express_number']) ? /*raise(1009,'缺少运单号')*/'' : $data['express_number'] ;//'123456789';//运单号

/*
        //判断单号是否能通过中通那边的匹配规则开始
        $rule = $this->getZtRule();//获取正则规则
logDebug($rule,'zt_thermalPaper_getRule');
logDebug($express_number,'zt_thermalPaper_expressNumber');
        if($rule){//规则不为空，进行验证
            $rule = '/'.$rule.'/';//拼接正则匹配规则
            $is_express_number_ok = preg_match($rule, $express_number);
logDebug($is_express_number_ok,'zt_thermalPaper_is_express_number_ok');
            if($is_express_number_ok !== 1){//0表示不匹配，1表示匹配，FALES表示出错所以采用!==1判断
                raise(1009,'单号不匹配！');
            }
        }
        unset($rule);
        //判断单号是否能通过中通那边的匹配规则结束
*/

        $datetime         = empty($data['datetime']) ? /*raise(1009,'缺少寄件时间')*/'' : $data['datetime'] ;//寄件时间

        $sender_name      = empty($data['sender_name']) ? /*raise(1009,'缺少发件人')*/'' : $data['sender_name'] ;//'变活扣旗舰店';//发件人
        $sender_phone     = empty($data['sender_phone']) ? /*raise(1009,'缺少发件人电话')*/'' : $data['sender_phone'];

        $sender_province  = empty($data['sender_province']) ? /*raise(1009,'缺少发件人省市区')*/'' : $data['sender_province'] ;
        $sender_city      = empty($data['sender_city']) ? /*raise(1009,'缺少发件人省市区')*/'' : $data['sender_city'] ;//'上海市,上海市,虹口区';//必填//发件人所在城市，如“上海市,上海市,青浦区,华新镇,华志路,123号”
        $sender_area      = empty($data['sender_area']) ? /*raise(1009,'缺少发件人省市区')*/'' : $data['sender_area'] ;
        $sender_address   = empty($data['sender_address']) ? /*raise(1009,'缺少发件人详细地址')*/'' : $data['sender_address'] ;//'三门路100号';//必填//发件人路名门牌等地址信息

        $receiver_name    = empty($data['receiver_name']) ? /*raise(1009,'缺少收件人')*/'' : $data['receiver_name'] ;//'尹静';//必填//收件人姓名

        $receiver_phone   = empty($data['receiver_phone']) ? /*raise(1009,'缺少收件人电话')*/'' : $data['receiver_phone'] ;

        $receiver_province= empty($data['receiver_province']) ? /*raise(1009,'缺少收件人省市区')*/'' : $data['receiver_province'] ;
        $receiver_city    = empty($data['receiver_city']) ? /*raise(1009,'缺少收件人省市区')*/'' : $data['receiver_city'] ;//'上海市,上海市,长宁区';//必填//收件人所在城市，如“上海市,上海市,青浦区,华新镇,华志路,123号”
        $receiver_area    = empty($data['receiver_area']) ? /*raise(1009,'缺少收件人省市区')*/'' : $data['receiver_area'] ;
        $receiver_address = empty($data['receiver_address']) ? /*raise(1009,'缺少收件人详细地址')*/'' : $data['receiver_address'] ;//'北翟路1178号（鑫达商务楼）1号楼415室';//必填//收件人路名门牌等地址信息

        $goods_name       = empty($data['goods_name']) ? /*raise(1009,'缺少货品名称')*/'' : $data['goods_name'] ;//选填//货品名称（物类型）
        //必填字段结束

        //以下为选填字段
        $charging_weight  = empty($data['charging_weight']) ? '' : $data['charging_weight'] ;//选填//计费重量
        $claiming_value   = empty($data['claiming_value']) ? '' : $data['claiming_value'] ;//选填//声明价值
        $collection_amount= empty($data['collection_amount']) ? '' : $data['collection_amount'] ;//选填//代收金额
        $to_pay_amount    = empty($data['to_pay_amount']) ? '' : $data['to_pay_amount'] ;//选填//到付金额
        $remark           = empty($data['remark']) ? '' : $data['remark'] ;//选填//备注
        //选填字段结束

        //需要存入orders.tbl_thermalpaper_order的数据
        $insert_data = array(
            //订单编号
            'order_number'     => $order_number,
            //快递公司
            'brand'            => 'zt',//中通
            //网点名称
            'branch_name'      => $branch_name,
            //快递员id
            'cm_id'            => $cm_id,
            //快递员姓名
            'cm_name'          => $cm_name,
            //快递员手机号
            'cm_phone'         => $cm_phone,
            //快递单号
            'express_number'   => $express_number,
            //发件人姓名
            'sender_name'      => $sender_name,
            //发件人电话
            'sender_phone'     => $sender_phone,
            //发件人省
            'sender_province'  => $sender_province,
            //发件人市
            'sender_city'      => $sender_city,
            //发件人区
            'sender_area'      => $sender_area,
            //发件人详细地址
            'sender_address'   => $sender_address,
            //收件人姓名
            'receiver_name'    => $receiver_name,
            //收件人电话
            'receiver_phone'   => $receiver_phone,
            //收件人省
            'receiver_province'=> $receiver_province,
            //收件人市
            'receiver_city'    => $receiver_city,
            //收件人区
            'receiver_area'    => $receiver_area,
            //收件人详细地址
            'receiver_address' => $receiver_address,
            //电子面单打印时间
            'print_time'       => date('Y-m-d H:i:s'),
            /*
            //以下字段暂时无需录入我司数据库
            //计费重量(选填)
            'charging_weight'  => $charging_weight,
            //声明价值(选填)
            'claiming_value'   => $claiming_value,
            //到付金额(选填)
            'to_pay_amount'    => $to_pay_amount,
            */
            //代收金额(选填)
            'collection_amount'=> $collection_amount,
            //物品类型(非必填)
            'goods_type'       => $goods_name,
            //备注信息(非必填)
            'remark'           => $remark
        );

        //获取branch_no,branch_name,emp_no,emp_name,emp_pwd,key,imei,openId参数
        $scan_access_info = \artisan\db::connect('kd_pda')->table('tbl_scan_courier_zt')->select('emp_no,emp_name,emp_pwd,cm_phone,branch_no,branch_name,key,imei,index_shop_id,home_shop_id')->getOne(array('cm_phone' => $cm_phone, 'switch' => 'on', 'state' => 'approve'));
//logdebug($scan_access_info,'zt_send_datas_scan_access_info');
        if(empty($scan_access_info)){
            return [];
            //raise(4016, "未成功绑定把枪账号！");//测试时，需要绑定过巴枪的快递员账号
        }else{
            $ztObj = new \soa\parter\zt\pda();
            $openId = \artisan\cache::get($scan_access_info['emp_no'] ."openid:");   //获取openid
            if(empty($openId)){//若无openid重新登录
                $ztObj->login($scan_access_info);
                $openId = \artisan\cache::get($scan_access_info['emp_no'] ."openid:");
                if(empty($openId)){
                    return [];
                    //raise(4016, "系统异常，请稍后重试");//测试时，需要绑定过巴枪的快递员账号
                }
            }
        }
//logdebug($openId,'zt_send_openId');
        //需要传给中通接口的参数
        $zt_data = [
            'CT' => 'ZTO',
            'VE' => '100',
            'DE' => '0',
            'VT' => '1',
            'T'  => '96',
            'S'  => $express_number,
            'FD' => $sender_address,
            'FS' => $datetime,
            'FR' => $sender_name,
            'FN' => $sender_phone,
            'FA' => $sender_province.'-'.$sender_city.'-'.$sender_area,
            'RD' => $receiver_address,
            'RR' => $receiver_name,
            'RN' => $receiver_phone,
            'RA' => $receiver_province.'-'.$receiver_city.'-'.$receiver_area,
            'JWG'=> $charging_weight,//计费重量
            'DS' => $collection_amount,//代收货款
            'DF' => $to_pay_amount,//到付款
            'BZ' => $remark,
            'WT' => $goods_name
        ];
        $str = '';
        foreach($zt_data as $k =>$v){
            $str .= $k.'='.$v;
            if($k != 'WT'){
                $str .='*';
            }
        }
        unset($zt_data);
//logdebug($str,'zt_send_str');
        $plength = mb_strlen($str,'UTF-8');
//logdebug($plength,'zt_send_plength');
        $xml = '<?xml version="1.0" encoding="utf-8" ?>
<root>
<h>
  <ver>4.0</ver>
  <optype>G036</optype>
  <manufacturer>KUAIBAOAPP</manufacturer>
  <u_company>'.$scan_access_info['branch_no'].'</u_company>
  <u_code>'.$scan_access_info['emp_no'].'</u_code>
  <sys_sn>'.$scan_access_info['imei'].'</sys_sn>
  <key>'.$scan_access_info['key'].'</key>
  <openid>'.$openId.'</openid>
</h> 
 <d>
  <h>'.$plength.'</h>
  <p>
   <a>'.$str.'</a>
  </p>
 </d>
</root>';
//logdebug(base64_encode(md5($xml.'123456', true)),'签名1');
//logdebug('before_xml','zt_send_before_xml');
//logdebug($xml,'zt_send_xml');
        $ret = $this->sendToZto($xml);//发送到中通//{"Success":{"optype":"G036","ver":"4.0","d":{"h":"159"}}}
//logdebug($ret,'zt_send_ret');
        //$ret = format::xml2array($ret);//
        if(isset($ret['Success'])){
            //录单成功；将is_send字段设为1（此字段默认为0，表示还未录单成功或者未录单过）
            $where['id'] = $order_number;
            $updateData['is_send'] = '1';
            if($collection_amount) {
                $updateData['collection_amount'] = $collection_amount;//更新orders.tbl_order表中的代收货款字段
            }
            $update = db::connect('orders')->table('tbl_order')->update($where,$updateData);
            if($update === false ){
                logdebug($order_number.'-'.$updateData,'updateZtOrder_isSend_false');
            }
            //更新is_send字段结束

            //调用热敏单公用方法（电子面单公用方法）
            //存入我司数据库
            $partnerCommonObj = new partnerCommon();
            $insert_ret = $partnerCommonObj->saveThermalPaperOrder($insert_data);
            if(!$insert_ret){
                logdebug($insert_data,'zt_saveThermalPaperOrder');
            }

            //return  $ret;
            return [];
        }else{
            //return 'faild';//"error":{"reason":"XXX"}
            return [];
        }
    }

    /**
     * 打包数据发送到中通
     * @param $xml
     * @return array|bool|string
     */
    private final function sendToZto($xml){
            (mb_internal_encoding('UTF-8'));
            $post = array(
                'data_xml'  => mb_convert_encoding($xml, 'GBK'),
                'data_sign' => ( base64_encode(md5($xml.'123456', true)) ),
                'data_user' => 'KUAIBAOAPP',
                'data_ver' => '4.0'
            );


            $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:multipart/form-data; charset=utf-8',
                'content' => http_build_query($post)
            )
        );

        //$context = stream_context_create($options);
        $ret = format::xml2array(
            http::post('http://pda.zto.cn/pda.zto', $post, array('HTTPHEADER' => array(
            'Content-type:multipart/form-data; charset=utf-8'
        ))));
        if(isset($ret['Success'])){
            return $ret;
        }else{
            return false;
        }

        // try {
        //     $ret = format::xml2array(
        //         http::post('http://pda.zto.cn/pda.zto', $post, array('HTTPHEADER' => array(
        //         'Content-type:multipart/form-data; charset=utf-8'
        //     ))));
        //     if(isset($ret['error']['reason']) && strpos($ret['error']['reason'], 'KEY值不对应') !== false) {
        //         $this->refreshKey();
        //     }
        //     return $ret;
        // } catch(\Exception $e) {
        //     logDebug($e->getCode() . ':' . $e->getMessage(), 'ztf_open');
        //     return false;
        // } finally {
        //     if(isset($fp))
        //         fclose($fp);
        // }
    }
}